package com.bf.electroplating.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bf.electroplating.pojo.dto.RainfallSiteListResponseDTO;
import com.bf.electroplating.pojo.entity.RainfallOutletSite;
import com.bf.electroplating.service.IRainfallSiteListSyncService;
import com.bf.electroplating.service.IRainfallOutletSiteService;
import com.bf.electroplating.util.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 雨排口站点列表同步服务实现类
 *
 * @author system
 * @since 2025-01-11
 */
@Slf4j
@Service
public class RainfallSiteListSyncServiceImpl implements IRainfallSiteListSyncService {

    @Autowired
    private IRainfallOutletSiteService rainfallOutletSiteService;

    @Value("${company.api.baseUrl}")
    private String apiBaseUrl;

    @Value("${company.api.secret}")
    private String apiSecret;

    private final RestTemplate restTemplate = new RestTemplate();

    @Override
    public void syncRainfallSiteList() {
        log.info("开始同步雨排口站点列表数据");
        
        try {
            // 调用6.4接口获取站点列表
            String response = callRainfallSiteListAPI();
            
            // 解析响应数据
            RainfallSiteListResponseDTO responseDTO = JSON.parseObject(response, RainfallSiteListResponseDTO.class);
            
            if (responseDTO == null || !responseDTO.getSuccess() || responseDTO.getData() == null) {
                log.warn("雨排口站点列表API返回失败或为空");
                return;
            }

            // 保存站点数据到数据库
            saveRainfallSiteList(responseDTO.getData());
            
            log.info("雨排口站点列表数据同步完成，共处理 {} 个站点", responseDTO.getData().size());
        } catch (Exception e) {
            log.error("同步雨排口站点列表数据失败", e);
            throw new RuntimeException("同步雨排口站点列表数据失败: " + e.getMessage());
        }
    }

    /**
     * 调用雨排口站点列表API
     */
    private String callRainfallSiteListAPI() {
        try {
            String url = apiBaseUrl + "/out/site/list";
            
            // 6.4接口无需参数，传递空对象
            Object emptyBody = new Object();
            String encryptedParams = SignUtil.generateParams(emptyBody);
            
            log.debug("调用雨排口站点列表API: {}, 参数: {}", url, encryptedParams);
            
            // 发送POST请求
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            
            String response = restTemplate.postForObject(url, encryptedParams, String.class, headers);
            
            log.debug("雨排口站点列表API响应: {}", response);
            
            return response;
        } catch (Exception e) {
            log.error("调用雨排口站点列表API失败", e);
            throw new RuntimeException("调用雨排口站点列表API失败: " + e.getMessage());
        }
    }

    /**
     * 保存雨排口站点列表数据到数据库
     */
    private void saveRainfallSiteList(List<RainfallSiteListResponseDTO.SiteInfo> siteList) {
        if (siteList == null || siteList.isEmpty()) {
            return;
        }

        for (RainfallSiteListResponseDTO.SiteInfo siteInfo : siteList) {
            try {
                // 检查站点是否已存在
                RainfallOutletSite existingSite = rainfallOutletSiteService.getOne(
                        new LambdaQueryWrapper<RainfallOutletSite>()
                                .eq(RainfallOutletSite::getSiteId, siteInfo.getId())
                );

                RainfallOutletSite site = new RainfallOutletSite();
                
                if (existingSite != null) {
                    // 更新现有站点
                    site.setId(existingSite.getId());
                    site.setSiteId(siteInfo.getId());
                    site.setSiteName(siteInfo.getSiteName());
                    site.setSiteAddr(siteInfo.getSiteAddr());
                    site.setIndustryName(siteInfo.getIndustryName());
                    site.setBaselineValue(siteInfo.getBaselineValue());
                    site.setSiteStatus(siteInfo.getSiteSts());
                    site.setParkId("1001");
                    rainfallOutletSiteService.updateById(site);
                    log.debug("更新站点: {}", siteInfo.getSiteName());
                } else {
                    // 插入新站点
                    site.setSiteId(siteInfo.getId());
                    site.setSiteName(siteInfo.getSiteName());
                    site.setSiteAddr(siteInfo.getSiteAddr());
                    site.setIndustryName(siteInfo.getIndustryName());
                    site.setBaselineValue(siteInfo.getBaselineValue());
                    site.setSiteStatus(siteInfo.getSiteSts());
                    site.setParkId("1001");
                    rainfallOutletSiteService.save(site);
                    log.debug("新增站点: {}", siteInfo.getSiteName());
                }
            } catch (Exception e) {
                log.error("保存站点数据失败: {}", siteInfo.getSiteName(), e);
            }
        }

        log.info("成功保存 {} 个雨排口站点数据", siteList.size());
    }
}
